package com.crm.controller.productionController;

import com.crm.exception.ServiceException;
import com.crm.pojo.ProductionDetail;
import com.crm.pojo.Productioncategory;
import com.crm.service.productionService.ProductionCategoryServiceImpl;
import com.crm.service.productionService.ProductionDetilsService;
import com.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PCategoryController {
    @Autowired
    private ProductionCategoryServiceImpl productionCategoryServiceImpl;
    @Autowired
    private ProductionDetilsService productionDetilsService;
    //查看所有的分类
    @PostMapping("allProCategories")
    @ResponseBody
    public Map allProCategories(int page, int rows){
        Long total =  productionCategoryServiceImpl.queryCount();
        List<Productioncategory>  productioncategories= productionCategoryServiceImpl.allProductionCategoryPaged(page,rows);
        Map map = new HashMap<>();
        map.put("total",total);
        map.put("rows",productioncategories);
        return map;
    }
    //产品分类页面
    @GetMapping("pCategory")
    public  String pCategory(){
        return "product/productionCategory";
    }
    //新建分类表单
    @GetMapping("to-form-proC")
    public String toFormProC(){
        return "product/procategoryAdd";
    }
    //删除分类表单
    @GetMapping("to-form-proC-delete")
    public String toFormProCDel(){
        return "product/procategoryDel";
    }
    //模糊查询（根据pcid或者pcname）
    @PostMapping("getAllCategoryBymh")
    @ResponseBody
    public List<Productioncategory> getAllCategoryBymh(String q){
        return productionCategoryServiceImpl.queryBypcidOrpcnameMh(q);
    }
    @PostMapping("getAllCategoryBymh2")
    @ResponseBody
    public List<Productioncategory> getAllCategoryBymh2(String q, String noteq){
        return productionCategoryServiceImpl.queryBypcidOrpcnameMh(q,noteq);
    }
    //添加产品分类
    @PostMapping("newProC-form-sub")
    @ResponseBody
    public Result addNewProC(Productioncategory productioncategory){
        Result r =new Result();
        try {
            productioncategory.setProductioncategoryIsDel("未删除");
            if(productioncategory.getPcpid()==null||productioncategory.getPcpid()==0){
                productioncategory.setPcpid(0L);
                productioncategory.setPcdepth(1L);
            }else{
                if(productionCategoryServiceImpl.queryOneById(productioncategory.getPcpid())==null){
                    return new Result("父分类不存在，添加分类失败！");
                }else {
                    Productioncategory father =  productionCategoryServiceImpl.queryOneById(productioncategory.getPcpid());
                    productioncategory.setPcdepth(father.getPcdepth()+1L);
                }
            }
            productionCategoryServiceImpl.addCategory(productioncategory);
        }catch (Exception e){
            r.setSuccess(false);
            r.setMessage("添加分类失败！");
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return r;
    }
    //删除产品分类
    @PostMapping("pro-categorys-del")
    @ResponseBody
    public Result proCategoriesDel(String rowsId){
        String[] idsS = rowsId.split(",");
        Long[] ids=new Long[idsS.length];
        for(int i =0;i<idsS.length;i++){
            ids[i] = Long.parseLong(idsS[i]);
        }
        try{
            for(int i = 0; i < ids.length;i++){
                Productioncategory productioncategory = productionCategoryServiceImpl.queryOneById(ids[i]);
                productioncategory.setProductioncategoryIsDel("已删除");
                productionCategoryServiceImpl.updateCategory(productioncategory);
                Long nowId = ids[i];
                //用于装载所有子节点id
                List<Long> listIds = new ArrayList<Long>();
                while (!productionCategoryServiceImpl.querySomeByPcpid(nowId).isEmpty()||!listIds.isEmpty()) {
                    if(!listIds.isEmpty()){
                        listIds.remove(0);
                    }
                    if(!productionCategoryServiceImpl.querySomeByPcpid(nowId).isEmpty()) {
                        for (Productioncategory pc :
                                productionCategoryServiceImpl.querySomeByPcpid(nowId)) {
                            pc.setProductioncategoryIsDel("已删除");
                            productionCategoryServiceImpl.updateCategory(pc);
                            listIds.add(pc.getPcid());
                        }
                    }else{
                        List<ProductionDetail> pList = new ArrayList<>();
                        pList  = productionCategoryServiceImpl.queryPdsByPcid(nowId);
                        if(!pList.isEmpty()) {
                            for (ProductionDetail p : pList) {
                                p.setPcategory(null);
                                productionDetilsService.updateProduction(p);
                            }
                        }
                    }
                    if(!listIds.isEmpty()){
                        nowId = listIds.get(0);
                    }
                }
                //特殊情况
                List<ProductionDetail> pList2 = new ArrayList<>();
                pList2  = productionCategoryServiceImpl.queryPdsByPcid(nowId);
                for (ProductionDetail p:pList2){
                    p.setPcategory(null);
                    productionDetilsService.updateProduction(p);
                }

            }
            return Result.SUCCESS;
        }catch (ServiceException e){
            e.printStackTrace();
            return new Result("删除失败！");
        }

    }
    //打开编辑表单
    @GetMapping("to-form-proC-update")
    public String toFormProCUpdate(){
        return "product/updateProC";
    }

    //根据pcid查询一个分类信息
    @GetMapping("getRowData")
    @ResponseBody
    public Productioncategory getRowData(Long pcid){
        return productionCategoryServiceImpl.queryOneById(pcid);
    }
    //提交表单修改数据
    @PostMapping("editProC-form-sub")
    @ResponseBody
    public Result editProC(Productioncategory productioncategory){
        try {
            productioncategory.setProductioncategoryIsDel("未删除");
            if(productioncategory.getPcpid()==null){
                productioncategory.setPcpid(productionCategoryServiceImpl.queryOneById(productioncategory.getPcid()).getPcpid());
            }else{
                if(productioncategory.getPcpid()==0){
                    productioncategory.setPcdepth(1L);
                }else if(productionCategoryServiceImpl.queryOneById(productioncategory.getPcpid())==null){
                    return  new Result("修改失败！父分类不存在！");
                }else {
                    productioncategory.setPcdepth(productionCategoryServiceImpl.queryOneById(productioncategory.getPcpid()).getPcdepth()+1L);
                }
            }
            productionCategoryServiceImpl.updateCategory(productioncategory);
            return Result.SUCCESS;
        }catch (ServiceException e){
            e.printStackTrace();
            return new Result("修改失败！");
        }
    }
    //打开产品分类详情
    @GetMapping("to-form-proC-details")
    public String toFormProcDetails(){
        return "product/detailsProC";
    }
    //打开高级查询表单
    @GetMapping("to-form-proC-highLevel")
    public String toFormProcHighLevel(){
        return "product/formProChl";
    }
    //高级查询表单提交
    @PostMapping("ProC-form-hlq-sub")
    @ResponseBody
    public Map proCFormhlq(Productioncategory productioncategory, int page, int rows){
            Map map = new HashMap<>();
            Long count = productionCategoryServiceImpl.proChlqCount(productioncategory);
            List<Productioncategory> productioncategories = productionCategoryServiceImpl.proChlq(productioncategory,page,rows);
            map.put("total",count);
            map.put("rows",productioncategories);
            return map;
    }


}
